package com.zx.jhpt.datamart;

import com.zx.framework.core.exception.ServiceException;
import com.zx.framework.core.util.DatetimeUtils;
import com.zx.framework.core.util.RandomUtil;
import com.zx.framework.core.util.SpringBeanUtil;
import com.zx.framework.core.util.StringUtil;
import com.zx.framework.db.IBaseDAO;
import com.zx.jhpt.excel.vo.ImportColumn;
import com.zx.jhpt.excel.vo.Risk;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service("logDynamicService")
@Transactional(transactionManager = "logTransactionManager")
public class LogDynamicService {

    private static final Logger LOGGER = Logger.getLogger(LogDynamicService.class);
    @Resource
    IBaseDAO baseDAO;


    /**
     * 执行数据同步
     *
     * @param dataMart
     * @return
     */
    public void synData(DataMart dataMart) {
        try {
            List<Map<String, Object>> list = pullData(dataMart);
            insertData(dataMart, list);
        } catch (Exception e) {
            LOGGER.error("数据同步出错..." + e.getMessage());
            throw new ServiceException("数据同步出错!" + e.getMessage());
        }
    }

    /**
     * 拉取对应表数据
     *
     * @param dataMart
     * @return
     */
    public List<Map<String, Object>> pullData(DataMart dataMart) {
        validate(dataMart);
        try {
            IBaseDAO dao = SpringBeanUtil.getBean(dataMart.getMarkDao(), IBaseDAO.class);
            String tableName = dataMart.getRemoteTableName();
            //查询符合条件的数据
            String column = "";
            for (Column c : dataMart.getColumns()) {
                column += c.getName().toUpperCase() + ",";
            }
            column = column.substring(0, column.length() - 1);
            String sql = "SELECT " + column + " from " + tableName + " where cycle = ?";
            List<Map<String, Object>> list = dao.querySQL(sql, DatetimeUtils.dateToString(new Date(), "yyyy-MM-dd"));
            return list;
        } catch (Exception e) {
            LOGGER.error("数据拉取出错..." + e.getMessage());
            throw new ServiceException("数据拉取出错!" + e.getMessage());
        }
    }

    /***
     * 验证数据完整性
     *
     * @param dataMart
     */
    private void validate(DataMart dataMart) {
        if (StringUtil.isEmpty(dataMart.getTableName())) {
            throw new ServiceException("数据拉取的目标数据库设置[tableName]不存在，请检查!");
        }
        if (StringUtil.isEmpty(dataMart.getMarkDao())) {
            throw new ServiceException("数据拉取的目标数据库设置[markDao]不存在，请检查!");
        }
        if (dataMart.getColumns().size() == 0) {
            throw new ServiceException("数据拉取的目标数据库设置[columns]不存在，请检查!");
        }
    }

    /**
     * 插入拉取到的数据到指定表
     *
     * @param datas
     */
    public void insertData(DataMart dataMart, List<Map<String, Object>> datas) {
        try {
            //删除数据的依据条件
            String sql = "delete from " + dataMart.getTableName() + " where zx_time = ?";
            baseDAO.executeSQL(sql, DatetimeUtils.dateToString(new Date(),"yyyy-MM-dd"));
            //整理插入语句
            sql = "insert into " + dataMart.getTableName();
            sql += " (";
            StringBuilder sb = new StringBuilder();
            StringBuilder sb1 = new StringBuilder();
            List<String> cls = new ArrayList<String>();
            for (Column column : dataMart.getColumns()) {
                sb.append(column.getName() + ",");
                sb1.append("?,");
                cls.add(column.getName());
            }
            //加入CYCLE,REMOTETABLENAME,MARKDAO,OPERATORID
            sb.append("CYCLE,");
            sb1.append("?,");

            sb.append("REMOTETABLENAME,");
            sb1.append("?,");

            sb.append("MARKDAO,");
            sb1.append("?,");

            sb.append("OPERATORID,");
            sb1.append("?,");

            sb.append("CYCLEPATTERN,");
            sb1.append("?,");

            sql += sb.subSequence(0, sb.length() - 1);
            sql += ") values (";
            sql += sb1.substring(0, sb1.length() - 1);
            sql += ") ";
            String cycle = null;
            String operatorid = null;
            String cyclePattern = null;
            //处理插入数据
            for (int i = 0; i < datas.size(); i++) {
                List<Object> params = new ArrayList<Object>();
                for (String c : cls) {
                    if (c.toUpperCase().equals("ZX_ID")) {
                        params.add(RandomUtil.getUUID());
                    }
                    else if (c.toUpperCase().equals("DEAL_DATE")) {
                        cycle = (String) datas.get(i).get(c.toUpperCase());
                        params.add(cycle);
                    }
                    else if (c.toUpperCase().equals("ACCEPT_OPERATOR")) {
                        operatorid = (String) datas.get(i).get(c.toUpperCase());
                        params.add(operatorid);
                    }
                    else if (c.toUpperCase().equals("ZX_TIME")) {
                        params.add(DatetimeUtils.dateToString(new Date(),"yyyy-MM-dd"));
                    }
                    else {
                        params.add(datas.get(i).get(c.toUpperCase()));
                    }
                }
                params.add(cycle);
                params.add(dataMart.getRemoteTableName());
                params.add(dataMart.getMarkDao());
                params.add(operatorid);
                params.add(dataMart.getCyclePattern());
                baseDAO.executeSQL(sql, params.toArray());
            }
        } catch (Exception e) {
            LOGGER.error("数据插入出错..." + e.getMessage());
            throw new ServiceException("数据插入出错" + e.getMessage());
        }
    }
}
